<script setup lang="ts">
import { ContentWrapNoHeaderLine } from '@/components/ContentWrap'
import { useIcon } from '@/hooks/web/useIcon'
import { Table } from '@/components/Table'
import {
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElInput,
  ElButton,
  ElSpace,
  ElDivider,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElCheckbox,
  ElTabs,
  ElTabPane,
  ElMessage
} from 'element-plus'
import { reactive, ref, h, watch, unref } from 'vue'
import { useTable } from "@/hooks/web/useTable";
import { OrgData } from "@/api/org/types";
import { getOrgDetailApi, getOrgListApi, saveOrUpdateOrg, delOrgApi } from "@/api/org/index";
import { Pagination, TableColumn } from "@/types/table";
import Edit from "./edit.vue";
import EquipmentEdit from "./equipmentEdit.vue";
import OtherEdit from "./otherEdit.vue";
import CheckForm from "./check.vue";
import { Dialog } from '@/components/Dialog'
import { FormSchema } from "@/types/form";
import { useValidator } from "@/hooks/web/useValidator";

const { required, isEqual } = useValidator()

const queryModel = reactive<Recordable>({
  status: '',
  column: '',
  val: '',
})

const columns = reactive<TableColumn[]>([
  {
    field: 'id',
    label: 'ID',
    search: false,
    visible: true,
    className: ''
  }, {
    field: 'companyId',
    label: '组织ID',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'name',
    label: '组织/用户名称',
    visible: true,
    search: true,
    className: ''
  }, {
    field: 'code',
    label: '组织机构代码/身份证',
    visible: true,
    search: true,
    className: ''
  }, {
    field: 'apply',
    label: '申请人姓名',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'phone',
    label: '申请人手机号',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'status',
    label: '状态',
    visible: true,
    className: ''
  }, {
    field: 'action',
    label: '操作',
    visible: true,
    className: ''
  }
])

const { register, tableObject, methods } = useTable<OrgData>({
  getListApi: getOrgListApi,
  delListApi: delOrgApi,
  response: {
    list: 'list',
    total: 'total'
  }
})
const paginationObj = ref<Pagination>()
watch(() => tableObject.total,
  (val) => {
    if (val > 0) {
      paginationObj.value = {
        total: tableObject.total
      }
    } else {
      paginationObj.value = undefined
    }
  })
const { getList, setSearchParams } = methods
getList()

const icons = {
  plusIcon: useIcon({ icon: 'ph:plus-bold' }),
  deleteIcon: useIcon({ icon: 'ep:delete' }),
  playIcon: useIcon({ icon: 'material-symbols:play-circle' }),
  stopIcon: useIcon({ icon: 'material-symbols:stop-circle' })
}
const spacer = h(ElDivider, { direction: 'vertical' })

const handleQuery = () => {
  let queryParams: Recordable = {} as any
  if (queryModel.column) {
    queryParams[queryModel.column] = queryModel.val
  }
  setSearchParams({ queryParams })
}

const selectedCount = ref(0)
const multipleSelection = ref<OrgData[]>([])
const handleSelectionChange = (val: OrgData[]) => {
  multipleSelection.value = val
  selectedCount.value = val?.length || 0
}

const handleVisibleChange = (item) => {
  item.className = item.visible ? '' : 'hidden'
}

const dialogVisible = ref(false);
const dialogTitle = ref("");
const actionType = ref("");
const loading = ref(false)
const delLoading = ref(false)
const editRef = ref<ComponentRef<typeof Edit>>()
const editEquipmentRef = ref<ComponentRef<typeof EquipmentEdit>>()
const editOtherRef = ref<ComponentRef<typeof OtherEdit>>()
const save = async () => {
  const org = unref(editRef)
  const isUpdate = actionType.value == 'edit';
  await org?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = (await org?.getFormData()) as OrgData
      const res = await saveOrUpdateOrg(data, isUpdate)
        .catch(() => {
        })
        .finally(() => {
          loading.value = false
        })
      if (res) {
        dialogVisible.value = false
        tableObject.page_index = 1
        getList()
      }
    }
  })
}
const handleAdd = () => {
  tableObject.currentRow = {} as OrgData
  actionType.value = ''
  dialogTitle.value = '新增组织机构'
  dialogVisible.value = true
}
const handleEditButton = (row: OrgData) => {
  getOrgDetailApi(row.id).then(res => {
    tableObject.currentRow = res.data
    actionType.value = 'edit'
    dialogTitle.value = '修改组织机构'
    dialogVisible.value = true
  }).catch(() => {
    ElMessage.error("获取数据错误，请联系管理员！");
  });
}
const handleDeleteButton = async (row: OrgData | null, multiple: boolean) => {
  tableObject.currentRow = row
  const { delListByObj, getSelections } = methods
  const selections = await getSelections()
  delLoading.value = true
  await delListByObj(
    multiple ? selections : [row] as OrgData[], multiple
  ).finally(() => {
    delLoading.value = false
  })
}
const companyIdFormSchema =
  {
    field: 'companyId',
    label: '组织ID',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }

  } as FormSchema;
const validateEqualPassword = async (rule, value, callback) => {
  console.log(rule)
  console.log(value)
  const org = unref(editRef)
  const formData: OrgData = await org?.getFormData() as OrgData;
  if (formData.password && formData.again) {
    isEqual(formData.password, formData.again, callback, "两次输入的新密码不一致！");
  }
}
const formSchema = reactive<FormSchema[]>([
  {
    field: 'idType',
    label: 'ID分配',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '系统分配',
          value: '1'
        },
        {
          label: '组织机构代码',
          value: '2'
        },
        {
          label: '手动输入',
          value: '3'
        }
      ],
      onChange: (val) => {
        if (val == 3) {
          const org = unref(editRef)
          org?.addSchema(companyIdFormSchema, 1);
        } else {
          const org = unref(editRef)
          org?.delSchema(companyIdFormSchema.field);
        }
      }

    },
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'name',
    label: '组织名称',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'code',
    label: '统一社会信用代码',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'apply',
    label: '申请人姓名',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'phone',
    label: '申请人电话',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'email',
    label: '申请人邮箱',
    component: 'Input',
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'password',
    label: '登录密码',
    component: 'Input',
    formItemProps: {
      rules: [required(), { validator: validateEqualPassword }]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'again',
    label: '密码确认',
    component: 'Input',
    formItemProps: {
      rules: [required(), { validator: validateEqualPassword }]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'license',
    label: '组织证明',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'supervisor',
    label: '监督人',
    component: 'Input',
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'supervisorPhone',
    label: '监督人电话',
    component: 'Input',
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    }
  }
]);
const statusOptions = [
  { label: '禁用', value: 0 },
  { label: '启用', value: 1 }
]
const equipmentFormSchema = reactive<FormSchema[]>([
  {
    field: 'user_limit',
    label: '沙箱数量上限',
    component: 'Input',
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'user_space_limit',
    label: '沙箱空间上限',
    component: 'Input',
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'user_files_limit',
    label: '沙箱文件数量上限',
    component: 'Input',
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'data_limit',
    label: '秘文端数量上限',
    component: 'Input',
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'data_space_limit',
    label: '秘文端空间上限',
    component: 'Input',
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'data_snapshot_limit',
    label: '组织沙箱快照数上限',
    component: 'Input',
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'valid_time',
    label: '组织账户有效期',
    component: 'Input',
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    }
  }
]);
const otherFormSchema = reactive<FormSchema[]>([
  {
    field: 'ssdevice_ssvs_count',
    label: '数组端仓库最大数量',
    component: 'Input',
    componentProps: {
      slots: {
        prepend: true,
        append: true
      }
    },
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'ssdevice_max_space_one_ssvs',
    label: '数组端单仓库最大容量',
    component: 'Input',
    componentProps: {
      slots: {
        prepend: true,
        append: true
      }
    },
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'ssdevice_max_file_count_one_ssvs',
    label: '秘文端单仓库最大文件数',
    component: 'Input',
    componentProps: {
      slots: {
        prepend: true,
        append: true
      }
    },
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'ssdevice_storage_total_space',
    label: '每个秘文端最大容量',
    component: 'Input',
    componentProps: {
      slots: {
        prepend: true,
        append: true
      }
    },
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'ssdevice_storage_total_file_count',
    label: '秘文端最大文件数量',
    component: 'Input',
    componentProps: {
      slots: {
        prepend: true,
        append: true
      }
    },
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'state_snapshot',
    label: '快照设置',
    component: 'Switch',
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    },
    componentProps: {
      activeValue: statusOptions[1].value,
      activeText: statusOptions[1].label,
      inactiveText: "",
      inactiveValue: statusOptions[0].value
    },
  },
  {
    field: 'state_share',
    label: '分享设置',
    component: 'Switch',
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    },
    componentProps: {
      activeValue: statusOptions[1].value,
      activeText: statusOptions[1].label,
      inactiveText: "",
      inactiveValue: statusOptions[0].value
    },
  },
  {
    field: 'state_log',
    label: '审计设置',
    component: 'Switch',
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    },
    componentProps: {
      activeValue: statusOptions[1].value,
      activeText: statusOptions[1].label,
      inactiveText: "",
      inactiveValue: statusOptions[0].value
    },
  },
  {
    field: 'state_policy',
    label: '防泄漏设置',
    component: 'Switch',
    formItemProps: {
      required: true
    }, colProps: {
      span: 24
    },
    componentProps: {
      activeValue: statusOptions[1].value,
      activeText: statusOptions[1].label,
      inactiveText: "",
      inactiveValue: statusOptions[0].value
    },
  }
]);
const handleReset = () => {
  const edit = unref(editRef)
  edit?.elFormRef?.resetFields()
}
const stateOptions = [
  { value: '0', label: '未处理' },
  { value: '1', label: '已通过' },
  { value: '-1', label: '未通过' }
];

const handleCheckButton = (row: OrgData) => {
  getOrgDetailApi(row.id).then(res => {
    tableObject.currentRow = res.data
    actionType.value = 'check'
    checkDialogVisible.value = true;
  }).catch(() => {
    ElMessage.error("获取数据错误，请联系管理员！");
  });
}

const activeTabName = ref("baseInfo");

const checkDialogVisible = ref(false);
const checkFormSchema = reactive<FormSchema[]>([
  {
    field: 'defaultGroup',
    label: '组织元端名称',
    component: 'Input',
    formItemProps: {
      required: false
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'defaultGroup',
    label: '审核通过',
    component: 'Radio',
    componentProps: {
      options: [
        {
          label: '通过',
          value: '1'
        },
        {
          label: '拒绝',
          value: '2'
        }
      ]
    },
    formItemProps: {
      required: true
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'defaultGroup',
    label: '拒绝原因',
    component: 'Select',
    formItemProps: {
      required: true
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'defaultGroup',
    label: '拒绝说明',
    component: 'Input',
    componentProps: {
      type: 'textarea',
      rows: 3
    },
    formItemProps: {
      required: true
    }, colProps: {
      span: 24
    }
  }
]);
const checkEditRef = ref<ComponentRef<typeof CheckForm>>();

const uploadedLicense = (url: string) => {
  if (tableObject.currentRow)
    tableObject.currentRow.license = url;
}
</script>

<template>
  <ContentWrapNoHeaderLine title="组织机构管理">
    <div class="flex justify-between">
      <el-form :inline="true" ref="queryFormRef" :model="queryModel">
        <el-form-item>
          <el-space direction="horizontal" :size="0">
            <el-select v-model="queryModel.status" placeholder="请选择状态">
              <template v-for="col in stateOptions" :key="col.value">
                <el-option :label="`${col.label}`" :value="`${col.value}`" />
              </template>
            </el-select>
            <el-select v-model="queryModel.column" placeholder="请选择查询字段">
              <template v-for="col in columns">
                <el-option v-if="col.search" :label="`按${col.label}`" :key="col.field" :value="`${col.field}`" />
              </template>
            </el-select>
            <el-input v-model="queryModel.val" placeholder="请输入">
              <template #append>
                <el-button class="query-button" type="primary" @click="handleQuery">查询</el-button>
              </template>
            </el-input>
          </el-space>
        </el-form-item>
      </el-form>
      <el-button :icon="icons.plusIcon" type="primary" @click="handleAdd">新增组织机构</el-button>
    </div>
    <div class="rounded bg-gray-100 w-full flex justify-between px-1.5 py-2 mb-3.5">
      <el-space :size="10" :spacer="spacer">
        <div>已批量选择<span class="mx-1 text-[var(--el-color-primary)]">{{ selectedCount }}</span>条事项</div>
        <el-button :icon="icons.deleteIcon" link @click="handleDeleteButton(null, true)">批量删除</el-button>
      </el-space>
      <el-space :size="10">
        <el-dropdown trigger="click" :hide-on-click="false">
          <span class="el-dropdown-link">
            <Icon icon="icon-park-outline:config" class="cursor-pointer " />
          </span>
          <template #dropdown>
            <div class="flex flex-col p-2">
              <template v-for="column in columns">
                <el-checkbox v-if="column.field !== 'action'" v-model="column.visible" :label="column.label"
                  :key="column.field" size="small" @change="handleVisibleChange(column)" />
              </template>
            </div>
          </template>
        </el-dropdown>
        <el-dropdown trigger="click">
          <span class="el-dropdown-link">
            <Icon icon="bi:download" class="cursor-pointer " />
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>导出到Csv</el-dropdown-item>
              <el-dropdown-item>导出到Excle</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <Icon icon="bi:printer" class="cursor-pointer " />
      </el-space>
    </div>
    <div class="">
      <Table border v-model:pageSize="tableObject.page_size" v-model:currentPage="tableObject.page_index"
        :columns="columns" :data="tableObject.tableList" :loading="tableObject.loading" :pagination="paginationObj"
        @register="register" @select="handleSelectionChange" @select-all="handleSelectionChange">
        <template #status="{ row }">
          <el-button v-if="row.status == '1'" class="!text-[#26C08D]" :icon="icons.playIcon" link>已通过</el-button>
          <el-button v-else-if="row.status == '-1'" class="!text-[#26C08D]" :icon="icons.playIcon" link>未通过</el-button>
          <el-button v-else :icon="icons.stopIcon" class="!text-[#FDC500]" link>未处理</el-button>
        </template>
        <template #action="{ row }">
          <el-space :size="6" :spacer="spacer">
            <ElButton v-if="row.status == '0'" type="primary" link @click="handleCheckButton(row)">
              审核
            </ElButton>
            <ElButton type="primary" link @click="handleEditButton(row)">
              编辑
            </ElButton>
            <ElButton type="primary" link @click="handleDeleteButton(row, false)">
              删除
            </ElButton>
          </el-space>
        </template>
      </Table>
    </div>
  </ContentWrapNoHeaderLine>
  <Dialog v-model="dialogVisible" :title="dialogTitle" :width="870" top="1vh" :max-height="'97%'">
    
    <Edit v-if="actionType != 'edit'" ref="editRef" @uploaded-license="uploadedLicense" :form-schema="formSchema"
          :current-row="tableObject.currentRow" />
    <el-tabs v-else v-model="activeTabName">
      <el-tab-pane label="基础信息" name="baseInfo">
        <Edit ref="editRef" @uploaded-license="uploadedLicense" :form-schema="formSchema"
          :current-row="tableObject.currentRow" />
      </el-tab-pane>
      <el-tab-pane label="设备信息" name="equipmentInfo">
        <EquipmentEdit ref="editEquipmentRef" :form-schema="equipmentFormSchema" :current-row="tableObject.currentRow" />
      </el-tab-pane>
      <el-tab-pane label="其他信息" name="otherInfo">
        <OtherEdit ref="editOtherRef" :form-schema="otherFormSchema" :current-row="tableObject.currentRow" />
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <ElButton @click="handleReset">重置</ElButton>
      <ElButton type="primary" :loading="loading" @click="save">
        提交
      </ElButton>
    </template>
  </Dialog>
  <Dialog v-if="checkDialogVisible" v-model="checkDialogVisible" :title="'审核'" :width="'70%'" top="2vh"
    :max-height="'97%'">
    <CheckForm ref="checkEditRef" :form-schema="checkFormSchema" :current-org="tableObject.currentRow"/>
    <template #footer>
      <ElButton @click="handleReset">重置</ElButton>
      <ElButton type="primary" :loading="loading" @click="save">
        提交
      </ElButton>
    </template>
  </Dialog>
</template>
